/**
 * 
 */
package com.googlecode.lohr.parser.combinators.matcher;


import java.util.ArrayList;

import com.googlecode.lohr.parser.combinators.MatchError;
import com.googlecode.lohr.parser.combinators.node.AbstractNode;

public class LongestMatcher extends ChoiceMatcher
{
	public LongestMatcher(Matcher... matchers)
	{
		super(matchers);
	}

	@Override
	public void match(final MatchContext ctx, final int start) 
	{
		final Matcher targetMatcher= this;
		final int targetStart= start;
		
		ctx.doMatch(new ChoiceMatcher(matchers), start, new MatchListener() {
			ArrayList<AbstractNode> _matches= new ArrayList<AbstractNode>();
			@Override
			public void onMatchFound(AbstractNode node) {
				_matches.add(node);
			}

			@Override
			public void onMatchComplete(MatchError matchError) {
				if (matchError != null) {
					ctx.matchComplete(targetMatcher, targetStart, matchError);
					return;
				}
				
				int longestLength= 0;
				for (AbstractNode node:_matches) {
					if (longestLength < node.length())
						longestLength= node.length();
				}
				for (AbstractNode node:_matches) {
					if (longestLength <= node.length())
						ctx.matchFound(targetMatcher, targetStart, node);
				}
				ctx.matchComplete(targetMatcher, targetStart);
			}
		});
	}
}